package com.example.forum_system.controller;

import com.example.forum_system.common.AppVar;
import com.example.forum_system.common.Result;
import com.example.forum_system.common.ResultCode;
import com.example.forum_system.model.Message;
import com.example.forum_system.model.User;
import com.example.forum_system.service.IMessageService;
import com.example.forum_system.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @BelongsProject: 0.forum_system
 * @BelongsPackage: com.example.forum_system.controller
 * @Author : 游在海里的鱼
 * @CreateTime : 2023-11-13  20:15
 * @Version : 1.0
 * @Description : TODO
 */
@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    IMessageService messageService;

    @PostMapping("/send")
    public Result addMessage(HttpServletRequest request, Message message,Long repliedId){
        //1.参数检验
        if(StringUtil.isEmpty(message.getContent())
                || message.getReceiveUserId() == null){
            log.error("文章传入参数异常");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2.得到当前登录用户对象
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppVar.SESSION_USER);
        //3.检查当前登录用户的状态
        if(user.getState() == 1){
            return Result.failed(ResultCode.FAILED_USER_BANNED);
        }
        //4.添加文章到数据库
        message.setPostUserId(user.getId());
        if(messageService.insertMessage(message) != 1){
            log.error("文章插入数据库失败");
            return Result.failed(ResultCode.FAILED_CREATE);
        }
        //5.
        if(repliedId != null && repliedId>=0){
            messageService.updateStateToReplied(repliedId);
        }
        //6.返回结果给前端
        return Result.success();
    }

    @GetMapping("/unrendCount")
    public Result getUnreadCount(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppVar.SESSION_USER);
        return Result.success(messageService.selectUnreadCount(user.getId()));
    }

    @GetMapping("/AllMessage")
    public Result getAllMessage(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppVar.SESSION_USER);
        return Result.success(messageService.selectAllMessage(user.getId()));
    }
}
